package com.ds.esd.admin.handler;

import com.ds.common.JDSException;
import com.ds.config.JDSUtil;
import com.ds.esd.client.ESDClient;
import com.ds.esd.client.ESDFacrory;
import com.ds.jds.core.esb.EsbUtil;
import com.ds.server.JDSClientService;
import com.ds.server.JDSServer;
import com.ds.server.httpproxy.core.*;
import com.ds.vfs.FileInfo;
import com.ds.vfs.ct.CtVfsFactory;
import com.ds.vfs.ct.CtVfsService;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;


public class ThumbnailHandler extends AbstractHandler implements Handler {
    private static final Logger log = Logger.getLogger(ThumbnailHandler.class.getName());

    public static final ConfigOption RESOURCE_MOUNT_OPTION = new ConfigOption("resourceMount", "/", "A path within the classpath to the root of the folder to share.");
    public static final ConfigOption DEFAULT_RESOURCE_OPTION = new ConfigOption("default", "index.html", "The default resource name.");
    public static final ConfigOption RULE_OPTION = new ConfigOption("rule", true, "Regular expression for matching URLs.");

    private String resourceMount;
    private String defaultResource;


    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        this.resourceMount = RESOURCE_MOUNT_OPTION.getProperty(server, handlerName);
        this.defaultResource = DEFAULT_RESOURCE_OPTION.getProperty(server, handlerName);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {
        String path = request.getPath();
        boolean ruleMatches = rule.matcher(path).matches();
        if (!ruleMatches) {
            return false;
        }

        String resource = Http.join(resourceMount, path.substring(getUrlPrefix().length()));
        if (resource.endsWith("/")) {
            resource += defaultResource;
        } else if (resource.lastIndexOf('.') < 0) {
            resource += "/" + defaultResource;
        }
        if (log.isLoggable(Level.INFO)) {
            log.info("Loading resource: " + resource);
        }
        String mimeType = getMimeType(resource);
        File file = new File(JDSUtil.getJdsRealPath() + resource);
        InputStream is = null;

        if (file.exists()) {
            is = new FileInputStream(file);
        } else {
            // 激活下载操作
            FileInfo fileInfo = null;
            try {
                JDSClientService clientService = null;
                clientService = EsbUtil.parExpression("$JDSC", JDSClientService.class);
                if (clientService == null) {
                    clientService = JDSServer.getInstance().getAdminClient();
                }
                ESDClient client = ESDFacrory.getESDClient(clientService);
                if (fileInfo == null) {
                    fileInfo = client.getFileByPath(path);
                }

                if (fileInfo != null) {
                    is = fileInfo.getCurrentVersonInputStream();
                    copyStreamToFile(is, file);
                    is = new FileInputStream(file);
                }

            } catch (JDSException e) {
                e.printStackTrace();
            }

            if (is != null) {
                response.setMimeType(mimeType);
                response.addHeader("Content-disposition", "filename=" + new String(fileInfo.getName().getBytes("utf-8"), "ISO8859-1"));
            }

        }


        if (mimeType == null || is == null) {
            log.warning("Resource was not found or the mime type was not understood. (Found file=" + (is != null) + ") (Found mime-type=" + (mimeType != null) + ")");
            return false;
        }
        response.setMimeType(mimeType);
        response.sendResponse(is, Integer.valueOf(Long.toString(file.length())));
        return true;
    }


    public CtVfsService getVfsClient() {
        CtVfsService vfsClient = CtVfsFactory.getCtVfsService();
        return vfsClient;
    }

}
